<template>
  <ElDialog
    v-model="visible"
    :title="isEdit ? '编辑小区' : '新增小区'"
    width="800px"
    top="4vh"
    :close-on-click-modal="false"
    @open="handleOpen"
    @close="handleClose"
  >
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="120px" label-position="right">
      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="小区名称" prop="areaName">
            <ElInput
              v-model="form.areaName"
              placeholder="请输入小区名称"
              maxlength="30"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="显示状态" prop="areaUpFlag">
            <ElSelect v-model="form.areaUpFlag" placeholder="请选择显示状态">
              <ElOption label="隐藏" :value="1" />
              <ElOption label="显示" :value="2" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="小区地址" prop="areaAddress">
            <div class="flex items-center w-full">
              <div class="flex-1">
                <el-input v-model="form.areaAddress" placeholder="请输入小区地址" />
              </div>
              <el-button class="ml-2" @click="openMapSelection">
                <el-icon>
                  <Location />
                </el-icon>
              </el-button>
            </div>
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="楼栋数" prop="areaHouseNum">
            <ElInputNumber
              v-model="form.areaHouseNum"
              :min="1"
              :max="9999"
              placeholder="请输入楼栋数"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="单元数" prop="areaUnitNum">
            <ElInputNumber
              v-model="form.areaUnitNum"
              :min="1"
              :max="9999"
              placeholder="请输入单元数"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="小区介绍" prop="areaInfo">
            <ElInput
              v-model="form.areaInfo"
              placeholder="请输入小区介绍"
              type="textarea"
              :rows="3"
              maxlength="500"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="小区规划图" prop="areaPlanInfo">
            <proUploadImg
              v-model:fileList="areaPlanInfo"
              action="/api/api/ossFile/saveFile"
              :maxSize="10"
              tip="图片大小不超过20MB"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="小区图片" prop="areaPhoto">
            <proUploadImg
              v-model:fileList="areaPhoto"
              action="/api/api/ossFile/saveFile"
              :maxSize="10"
              tip="图片大小不超过20MB"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <!-- 服务内容管理 -->
      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="服务内容" prop="geoAreaServeList">
            <div>
              <VueDraggable
                v-model="form.geoAreaServeList"
                :disabled="false"
                :prevent-on-filter="false"
                handle=".drag-handle"
              >
                <ElFormItem
                  v-for="(service, index) in form.geoAreaServeList"
                  :key="service.serveSort"
                  :prop="'geoAreaServeList.' + index + '.serveName'"
                  class="service-item"
                  :rules="{
                    required: true,
                    message: '服务内容不能为空',
                    trigger: 'blur'
                  }"
                >
                  <div class="flex items-center flex-col gap-2">
                    <div class="flex items-center gap-2 mb-2">
                      <!-- 拖拽手柄 -->
                      <div class="drag-handle cursor-move flex items-center text-gray-400">
                        <el-icon><Rank /></el-icon>
                      </div>
                      <!-- 序号 -->
                      <span class="w-6 text-center">{{ index + 1 }}</span>
                      <ElInput
                        v-model="service.serveName"
                        placeholder="请输入服务内容"
                        maxlength="10"
                        size="small"
                      />
                      <ElButton
                        type="danger"
                        size="small"
                        :icon="Delete"
                        @click="removeService(index)"
                      >
                        删除
                      </ElButton>
                    </div>
                  </div>
                </ElFormItem>
              </VueDraggable>
              <div>
                <ElButton type="primary" :icon="Plus" size="small" @click="addService">
                  添加服务
                </ElButton>
              </div>
            </div>
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="handleClose">取消</ElButton>
        <ElButton type="primary" :loading="loading" @click="handleSubmit"> 确定 </ElButton>
      </div>
    </template>
  </ElDialog>

  <MapSelection
    ref="mapSelectionRef"
    :title="mapSelectionDialog.title"
    :visible="mapSelectionDialog.visible"
    @getLocationSuccess="handleLocationSuccess"
    @mapClose="mapSelectionDialog.visible = false"
  />
</template>

<script setup lang="ts">
  import { ref, computed, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Plus, Delete, Rank } from '@element-plus/icons-vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import { geoAreaSaveDataUsingPost,geoAreaUpdateDataUsingPost, GeoAreaVo } from '@/api'
  import MapSelection from '@/components/core/map/index.vue'
  import { VueDraggable } from 'vue-draggable-plus'
  import { clone } from 'xe-utils'

  // 类型定义
  interface Props {
    modelValue: boolean
    areaData?: GeoAreaVo | null
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }

  // Props 和 Emits
  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    areaData: undefined
  })

  const emit = defineEmits<Emits>()

  // 响应式数据
  const formRef = ref<FormInstance>()

  const loading = ref(false)

  const areaPlanInfo = ref([])

  const areaPhoto = ref([])

  const initForm: GeoAreaVo = {
    areaName: '',
    areaAddress: '',
    areaLongitude: '',
    areaLatitude: '',
    areaHouseNum: 1,
    areaUnitNum: 1,
    areaUpFlag: 2,
    areaInfo: '',
    areaPlanInfo: '',
    areaPhoto: '',
    geoAreaServeList: []
  }

  const form = ref<GeoAreaVo>(clone(initForm, true))

  // 计算属性
  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  const isEdit = computed(() => !!props.areaData?.id)

  // 表单验证规则
  const rules: FormRules = {
    areaName: [
      { required: true, message: '请输入小区名称', trigger: 'blur' },
      { max: 30, message: '小区名称不能超过30个字符', trigger: 'blur' }
    ],
    areaAddress: [
      { required: true, message: '请输入小区地址', trigger: ['blur', 'change'] },
      {
        validator: (rule, value, callback) => {
          if (!value) {
            callback(new Error('请输入小区地址'))
            return
          }
          // 校验经度和纬度
          if (!form.value.areaLongitude || !form.value.areaLatitude) {
            callback(new Error('请选择小区位置（经度和纬度）'))
            return
          }
          callback()
        },
        trigger: ['blur', 'change']
      }
    ],
    areaHouseNum: [
      { required: true, message: '请输入楼栋数', trigger: 'blur' },
      { type: 'number', min: 0, max: 9999, message: '楼栋数应在0-9999之间', trigger: 'blur' }
    ],
    areaUnitNum: [
      { required: true, message: '请输入单元数', trigger: 'blur' },
      { type: 'number', min: 0, max: 9999, message: '单元数应在0-9999之间', trigger: 'blur' }
    ],
    areaUpFlag: [{ required: true, message: '请选择显示状态', trigger: 'change' }],
    areaInfo: [{ max: 500, message: '小区介绍不能超过500个字符', trigger: 'blur' }],
    areaPlanInfo: [
      {
        required: true,
        message: '请上传小区规划图',
        trigger: 'change',
        validator: (rule, value, callback) => {
          if (areaPlanInfo.value.length === 0) {
            callback(new Error('请上传小区规划图'))
            return
          }
          callback()
        }
      }
    ],
    areaPhoto: [
      {
        required: true,
        message: '请上传小区图片',
        trigger: 'change',
        validator: (rule, value, callback) => {
          if (areaPhoto.value.length === 0) {
            callback(new Error('请上传小区图片'))
            return
          }
          callback()
        }
      }
    ]
  }

  const mapSelectionRef = ref()

  const mapSelectionDialog = ref({
    visible: false,
    title: '选择位置'
  })

  // 打开地图选择
  const openMapSelection = () => {
    //初始化地图的经纬度，还有地址
    mapSelectionRef.value.initMapLatLng({
      longitude: form.value.areaLongitude || '114.3203',
      latitude: form.value.areaLatitude || '30.3505',
      address: form.value.areaAddress
    })
    mapSelectionDialog.value.visible = true
  }

  // 获取位置成功
  const handleLocationSuccess = (location: any) => {
    form.value.areaLongitude = location.longitude
    form.value.areaLatitude = location.latitude
    form.value.areaAddress = location.address
    mapSelectionDialog.value.visible = false
  }

  const addService = () => {
    form.value.geoAreaServeList?.push({
      serveName: '',
      serveSort: form.value.geoAreaServeList?.length + 1
    })
  }

  const removeService = (index: number) => {
    form.value.geoAreaServeList?.splice(index, 1)
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()

      loading.value = true
      if(isEdit.value){
        await geoAreaUpdateDataUsingPost({
        body: {
          ...form.value,
          areaPlanInfo: JSON.stringify(areaPlanInfo.value),
          areaPhoto: JSON.stringify(areaPhoto.value),
          geoAreaServeList: form.value.geoAreaServeList?.map((item, index) => ({
            serveName: item.serveName,
            serveSort: index + 1
          }))
        }
      })
      }else {
await geoAreaSaveDataUsingPost({
        body: {
          ...form.value,
          areaPlanInfo: JSON.stringify(areaPlanInfo.value),
          areaPhoto: JSON.stringify(areaPhoto.value),
          geoAreaServeList: form.value.geoAreaServeList?.map((item, index) => ({
            serveName: item.serveName,
            serveSort: index + 1
          }))
        }
      })

      }

      
      ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
      emit('success')
    } finally {
      loading.value = false
    }
  }

  const handleOpen = () => {
    if (isEdit.value) {
      areaPlanInfo.value = JSON.parse(props.areaData?.areaPlanInfo || '[]')
      areaPhoto.value = JSON.parse(props.areaData?.areaPhoto || '[]')
      nextTick(() => {
        form.value = clone(props.areaData as GeoAreaVo, true)
      })
    } else {
      form.value = clone(initForm, true)
    }
  }

  const handleClose = () => {
    formRef.value?.resetFields()
    areaPlanInfo.value = []
    areaPhoto.value = []
    nextTick(() => {
      visible.value = false
    })
  }
</script>

<style lang="scss" scoped>
  :deep(.service-item) {
    .el-form-item__content {
      .el-form-item__error {
        margin-top: -12px;
        margin-left: 46px;
      }
    }
  }

  .dialog-footer {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  }
</style>
